import $api from "@/api/index.js"
import $util from "@/utils/index.js"
import $store from "@/store/index.js"
var jweixin = require('jweixin-module');

export default {
	//判断是否在微信中    
	isWechat() {
		var ua = window.navigator.userAgent.toLowerCase()
		return 'micromessenger' == ua.match(/micromessenger/i)
	},
	async initJssdk(fn) {
		if (this.isWechat()) {
			let isWxReady = this.wxReady2()
			isWxReady.then(result => {
				console.log(result, "===isWxReady result")
				fn()
			}, (error) => {
				console.log(error, "===isWxReady error")
				this.toInitJssdk(fn)
			})
		} else {
			fn()
			console.log('不是微信端 initJssdk')
		}
	},
	async toInitJssdk(fn) {
		console.log(`toInitJssdk`)
		let {
			isConsole = false
		} = $store.state.user
		let page = window.entryUrl
		let webConfig = {}
		try {
			webConfig = await $api.base.getWebConfig({
				page
			})
		} catch (error) {
			console.log(`getWebConfig 失败`, page, error)
			if (isConsole) {
				$util.showToast({
					title: `webConfig--fail`
				})
			}
			webConfig = await $api.base.getWebConfig({
				page
			})
		}
		if (isConsole) {
			$util.showToast({
				title: JSON.stringify(webConfig)
			})
		}
		let {
			appid: appId,
			timestamp,
			nonceStr,
			signature
		} = webConfig
		console.log(`webConfig--${timestamp}`)
		if (isConsole) {
			$util.showToast({
				title: `webConfig--${timestamp}`
			})
		}
		try {
			if (timestamp) {
				jweixin.config({
					debug: false,
					appId,
					timestamp,
					nonceStr,
					signature,
					jsApiList: [ //这里是需要用到的接口名称  
						'checkJsApi', //判断当前客户端版本是否支持指定JS接口 
						'getLocation', //获取位置
						'updateAppMessageShareData',
						'updateTimelineShareData',
						'onMenuShareAppMessage',
						'onMenuShareTimeline',
						'hideOptionMenu',
						'showOptionMenu',
						'showMenuItems',
						'scanQRCode',
						'requestMerchantTransfer' // 确认收款
					],
					openTagList: ['wx-open-launch-weapp']
				})
				if (isConsole) {
					$util.showToast({
						title: `jwexin-config-suc`
					})
				}
				fn()
			} else {
				fn()
			}
		} catch (error) {
			if (isConsole) {
				$util.showToast({
					title: `jwexin-config-fail`
				})
			}
			console.log('jweixin.config 无响应')
			fn()
		}
	},
	wxReady: function(fn) {
		if (this.isWechat()) {
			jweixin.ready(function() {
				fn()
			})
		} else {
			console.log('不是微信端 wxReady')
		}
	},
	async wxReady2() {
		return new Promise((resolve, reject) => {
			let isReady = true
			setTimeout(() => {
				if (isReady) {
					reject(1)
				}
			}, 1000)
			jweixin.ready(function() {
				isReady = false
				resolve(1)
			})
		})
	},
	// 关闭右上菜单
	async hideOptionMenu() {
		this.wxReady(() => {
			jweixin.hideOptionMenu()
		})
	},
	// 开启右上菜单
	showOptionMenu: function() {
		this.wxReady(() => {
			jweixin.showOptionMenu()
			jweixin.showMenuItems({
				menuList: [
					'menuItem:share:appMessage',
					'menuItem:share:timeline'
				]
			})
		})
	},
	/*分享给微信朋友*/
	shareAppMessage: function(title, desc, link, imgUrl) {
		this.wxReady(() => {
			jweixin.updateAppMessageShareData({
				title,
				desc,
				link,
				imgUrl,
				success: function(res) {}
			})
			jweixin.onMenuShareAppMessage({
				title,
				desc,
				link,
				imgUrl,
				success: function(res) {}
			})
		})
	},
	/*分享微信朋友圈*/
	shareTimelineMessage: function(title, link, imgUrl) {
		this.wxReady(() => {
			jweixin.updateTimelineShareData({
				title,
				link,
				imgUrl,
				success: function(res) {}
			})
			jweixin.onMenuShareTimeline({
				title,
				link,
				imgUrl,
				success: function(res) {}
			})
		})
	},
	/*扫码*/
	async scanQRCode(type = 0) {
		$util.showLoading()
		try {
			return new Promise((resolve, reject) => {
				let methodModel = type ? 'initJssdk' : 'toInitJssdk'
				this[methodModel](() => {
					jweixin.ready(function() {
						$util.hideAll()
						jweixin.scanQRCode({
							needResult: 1,
							success: function(res) {
								console.log(res, "=====res scanQRCode")
								resolve(res.resultStr)
							}
						})
					})
				})
			})
		} catch (error) {
			$util.hideAll()
		}
	},
	/*确认收款*/
	async requestMerchantTransfer(param) {
		return new Promise((resolve, reject) => {
			try {
				this.initJssdk(() => {
					jweixin.ready(function() {
						$util.hideAll()
						jweixin.checkJsApi({
							jsApiList: ['requestMerchantTransfer'],
							success: function(res) {
								if (res.checkResult[
										'requestMerchantTransfer']) {
									WeixinJSBridge.invoke(
										'requestMerchantTransfer', param,
										function(res) {
											try {
												if (res.err_msg ==
													"requestMerchantTransfer:ok"
												) {
													resolve(true)
												} else {
													resolve(false)
												}
											} catch (e) {
												uni.showModal({content: JSON.stringify(res)})
											}
										}
									)
								} else {
									uni.showToast({
										title: '你的微信版本过低，请更新至最新版本'
									})
								}
							}
						})
					})
				})
			} catch (error) {
				resolve(false)
			}
		})
	},
	/*定位*/
	async getWxLocation() {
		return new Promise((resolve, reject) => {
			let location = {
				latitude: 0,
				longitude: 0
			}
			let {
				isConsole = false
			} = $store.state.user
			try {
				this.initJssdk(() => {
					jweixin.ready(function() {
						let isNotGet = true
						let isTimeOut = false
						setTimeout(() => {
							if (isNotGet) {
								isTimeOut = true
								if (isConsole) {
									$util.showToast({
										title: `5秒未获取到地址`
									})
								}
								resolve(location)
							}
						}, 5000)
						jweixin.getLocation({
							type: 'gcj02',
							cancel: function(res) {
								$util.showToast({
									title: `您已取消授权获取定位权限`
								})
							},
							complete: function(res) {
								isNotGet = false
								if (res.errMsg ===
									'getLocation:fail permission') {
									$util.showToast({
										title: `您已拒绝授权获取定位权限`
									})
								}
								if (!isTimeOut) {
									if (isConsole) {
										$util.showToast({
											title: JSON
												.stringify(
													res)
										})
									}
									resolve(res.errMsg ===
										'getLocation:ok' ? res :
										location)
								}
							}
						})
					})
					jweixin.error(function(e) {
						if (isConsole) {
							$util.showToast({
								title: `jwexin-error`
							})
						}
						console.log(e, "======jweixin.error")
						resolve(location)
					})
				})
			} catch (error) {
				resolve(location)
			}
		})
	},
}